package vsvm.data.source;

import java.io.BufferedReader;
import java.io.FileReader;

import vsvm.gui.Environment;

public abstract class FileDataSource extends AbstractDataSource {
	
	protected String filename;
	protected BufferedReader reader;
	
	public String getFilePath() {
		return filename;
	}
	
	public void setFilePath(String filename) {
		this.filename = filename;
	}
	
	public boolean open() {
		try {
			reader = new BufferedReader(new FileReader(filename));
		} catch (Exception e) {
			opened = false;
			return false;
		}
		
		opened = true;
		return true;		
	}
	
	public void close() {
		try {
			if (opened && reader != null) {
				reader.close();
				reader = null;
				opened = false;
			}
		} catch (Exception e) {}
	}

	@Override
	public void reset() {
		try {
			//if (opened && reader != null)
				//reader.reset();
			close();
			open();
		} catch(Exception e) {}
		
	}
	
	public String getRawData() {
		if (!opened) return "";
		
		StringBuilder sb = new StringBuilder();
		
		int i = 0;
		while (i < 20) {
			try {
				String s = reader.readLine();
				if (s == null) break;
				sb.append(s);
				sb.append(Environment.newline);
			} catch (Exception ex) { break; }
			++i;
		}
		
		return sb.toString();
	}

}
